package array;

import com.alibaba.fastjson2.JSON;

/**
 * description: <a href="https://leetcode.cn/problems/subarray-sum-equals-k/description/">560. 和为 K 的子数组</a>
 *
 * @author <a href="zhaoyingling12@163.com">simon zhao</a>
 * @since 2024/3/24
 */
public class SubArraySumEqualsK {

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 1, 2, 1};

        System.out.println(subarraySum(nums, 3));
    }

    public static int subarraySum(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int len = nums.length;

        // preSum[i] 表示 0 到 i - 1 之和
        int[] preSum = new int[len + 1];
        preSum[0] = 0;

        for (int i = 1; i < len; i++) {
            preSum[i] = preSum[i - 1] + nums[i - 1];
        }
        preSum[len] = preSum[len - 1] + preSum[len - 1];

        System.out.println("preSum " + JSON.toJSONString(preSum));

        int cnt = 0;
        for (int i = 0; i < len; i++) {
            for (int j = i; j < len; j++) {
                if ((preSum[j + 1] - preSum[i]) == k) {
                    cnt++;
                }
            }
        }
        return cnt;

    }
}
